
public class SteamKGram implements Steam<KGram> {

	KGram value;
	SteamKGram next;
	private int length;
	private boolean isEmpty;

	SteamKGram() {
		this.value = null;
		this.next = null;
		this.length = 0;
		this.isEmpty = true;
	}

	SteamKGram(KGram e, SteamKGram s) {
		this.value = e;
		this.next = s;
		if (s == null) {
			this.length = 1;
		}
		else {
			this.length = s.length() + 1;
		}
		this.isEmpty = false;
	}

	SteamKGram(SteamKGram s) {
		if (!s.isEmpty()) {
			this.value = new KGram(s.value);
			if (s.hasNext()) {
				this.next = new SteamKGram(s.next);
			}
			else {
				this.next = new SteamKGram();
			}
			this.length = s.length();
			this.isEmpty = s.isEmpty();
		}
		else {
			this.value = null;
			this.next = null;
			this.length = 0;
			this.isEmpty = true;
		}
	}

	public boolean hasNext() {
		return !this.next.isEmpty() ;
	}

	public boolean isEmpty() {
		return isEmpty;
	}

	public int length() {
		return this.length;
	}

	public KGram next() {
		if (this.hasNext()) {
			KGram v = this.value;
			this.value = this.next.value;
			this.length = this.next.length;
			this.isEmpty = this.next.isEmpty;
			this.next = this.next.next;
			return v;
		}
		if (!this.hasNext() && !this.isEmpty()) {
			KGram v = this.value;
			this.value = null;
			this.isEmpty = true;
			this.length = 0;
			return v;
		}
		if (this.isEmpty()) {
			throw new NullPointerException();
		}
		return null;
	}

	public void add(KGram e) {
		if (this.isEmpty()) {
			this.value = e;
			this.length = 1;
			this.next = new SteamKGram();
			this.isEmpty = false;
		}
		else {
			this.next = new SteamKGram(this.value, this.next);
			this.value = e;
			this.length = this.length + 1;
		}
	}

	public void print() {
		if (!this.isEmpty()) {
			if (this.hasNext()) {
				value.print();
				System.out.print(' ');
				this.next.print();
			}
			else {
				value.print();
				System.out.println();
			}
		}
	}

}
